<?php
/**
 * Created by PhpStorm.
 * User: liuwei
 * Date: 2022/12/16
 * Time: 14:19
 */

namespace App\Http\Controllers\Api;

use App\Http\Requests\ApiV2\FamilyMemberRequest;
use App\Http\Requests\ApiV2\FamilyRequest;

use App\Services\Member\Models\FamilyMember;
use Illuminate\Http\Request;
use App\Services\Member\Models\Family;

use Illuminate\Support\Facades\DB;

class FamilyController extends BaseController
{


    public function __construct()
    {


    }

    public function index(Request $request)
    {
        $page = $request->input('page', 1);
        $size = $request->input('size', 20);
        $query = Family::query()
            ->with(['user'])
            ->orderByDesc('id');
        $total = $query->count();
        $problems = $query->forPage($page, $size)->get()->toArray();

        return $this->successData(compact('problems', 'total'));
    }

    public function store(FamilyRequest $request, Family $family)
    {


        $userId = $this->id();
        $data = $request->filldata();
        $family->fill($data)->save();
        $family->member()->attach($userId);
        return $this->success("成功");
    }

    public function edit(FamilyRequest $request, $id)
    {
        $family = Family::query()->where('id', $id)->firstOrFail();
        return $this->successData(__(compact('family')));
    }



    public function update(FamilyRequest $request, $id)
    {
        $problem = Family::query()->where('id', $id)->firstOrFail();
        $data = $request->filldata();
        $problem->fill($data)->save();
        return $this->success(__('更新成功'));
    }


    public function delete($id)
    {
        $problem = Family::query()->where('id', $id)->firstOrFail();
        $problem->delete();
        return $this->success(__('问题删除成功'));
    }
    public function storeMember(Request $request, $id)
    {
        $family = Family::find($id);
        $userIds = $request->input('user_ids');
        $family->member()->attach($userIds);
        return $this->success(__('添加成功'));

    }

    public function createMember(FamilyMemberRequest $request, $id)
    {

        $family = Family::find($id);
        $data = $request->filldata();
        $family->member()->attach($data['user_id']);
        return $this->success(__('添加成功'));


    }

    public function deleteMember(Request $request, $id,$familyId)
    {

        $family = Family::find($id);
        $family->member()->detach($familyId);
        return $this->success(__('移除成功'));


    }

    public function editMember($id)
    {
        $member = FamilyMember::query()->where('id', $id)->first();
        return $this->successData(compact('member'));
    }



}